package com.xpc.consumer.spring.config;

import com.xpc.consumer.spring.scanner.reference.ReferenceScanner;
import com.xpc.rpc.consumer.config.RpcConsumerConfig;
import com.xpc.rpc.consumer.cache.RpcConsumerConfigCache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;


@Configuration
@EnableConfigurationProperties(RpcConsumerConfig.class)
public class RpcConsumerAutoConfig  implements InitializingBean, ApplicationContextAware {


    private static ApplicationContext applicationContext;

    @Resource
    private RpcConsumerConfig rpcConsumerConfig;

    @Override
    public void afterPropertiesSet() throws Exception {
        ReferenceScanner referenceScanner = new ReferenceScanner();
        referenceScanner.doScanDubboReferenceByPackage(rpcConsumerConfig.getPackageName());
        new RpcConsumerConfigCache(rpcConsumerConfig);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RpcConsumerAutoConfig.applicationContext = applicationContext;
    }

    public static Object getObject(Class clazz) {
        return applicationContext.getBean(clazz);
    }

    public static ApplicationContext getSpringContext() {
        return applicationContext;
    }
}
